<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useUserInfoStore } from '@/stores/UserInfo.ts'
import type { UserVO } from '@/api/User.ts'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const userInfo = ref<UserVO | null>(userInfoStore.currentUser)

const isCurrentUser = computed(() => {
  return userInfoStore.currentUser?.id === userInfo.value?.id
})

const solveRate = computed(() => {
  const submitNum = Number(userInfo.value?.submit ?? 0)
  const solvedNum = Number(userInfo.value?.solved ?? 0)
  if (!submitNum) return '0%'
  return ((solvedNum / submitNum) * 100).toFixed(2) + '%'
})

const genderMap: Record<number, string> = { 0: '男', 1: '女' }

const roleMap: Record<string, string> = {
  ROLE_ADMIN: '管理员',
  ROLE_USER: '普通用户',
  ROLE_SUPER_ADMIN: '超级管理员',
}

const getAvatarUrl = () =>
  'https://creative-3605.oss-cn-hangzhou.aliyuncs.com/creative-online-judge-prod/user/11801697558994_.pic.jpg!user_avatar'

const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

const goEdit = () => {
  if (userInfoStore.currentUser?.id) {
    router.push(`/user/edit/${userInfoStore.currentUser.id}`)
  } else {
    message.error('用户信息异常，无法编辑')
  }
}

const ensureLoginOrRedirect = async () => {
  if (!userInfoStore.currentUser) {
    message.error('请先登录')
    await router.push('/login')
    return false
  }
  return true
}

onMounted(async () => {
  const ok = await ensureLoginOrRedirect()
  if (!ok) return
  if (userInfoStore.currentUser?.id) {
    try {
      await userInfoStore.getUserInfo(userInfoStore.currentUser.id)
      userInfo.value = userInfoStore.currentUser
    } catch (error) {
      userInfo.value = userInfoStore.currentUser
    }
  } else {
    userInfo.value = userInfoStore.currentUser
  }
})
</script>

<template>
  <div class="max-w-[1200px] mx-auto p-4">
    <div class="rounded-lg shadow-md bg-white p-5">
      <div class="flex flex-col md:flex-row gap-6 md:items-center">
        <div class="flex items-center justify-center">
          <img :src="getAvatarUrl()" alt="avatar" class="w-28 h-28 rounded-full object-cover" />
        </div>
        <div class="flex-1">
          <h2 class="text-2xl font-semibold text-gray-900">{{ userInfo?.name }}</h2>
          <p class="text-gray-600 mt-2">
            {{ userInfo?.profile || '这个用户很懒，还没有填写个人简介' }}
          </p>
          <button v-if="isCurrentUser" class="mt-3 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700" @click="goEdit">
            编辑个人资料
          </button>
        </div>
      </div>

      <div class="my-6 border-t border-gray-100"></div>

      <div>
        <h3 class="text-lg font-medium text-gray-900 mb-3">个人信息</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
          <div class="border rounded p-3">
            <div class="text-gray-500">用户权限</div>
            <div class="mt-1 text-gray-900">{{ roleMap[userInfo?.role ?? ''] || '未知' }}</div>
          </div>
          <div class="border rounded p-3">
            <div class="text-gray-500">昵称</div>
            <div class="mt-1 text-gray-900">{{ userInfo?.name || '未设置' }}</div>
          </div>
          <div class="border rounded p-3">
            <div class="text-gray-500">性别</div>
            <div class="mt-1 text-gray-900">{{ genderMap[userInfo?.gender ?? 0] || '未设置' }}</div>
          </div>
          <div class="border rounded p-3">
            <div class="text-gray-500">邮箱</div>
            <div class="mt-1 text-gray-900 break-all">{{ userInfo?.email || '未设置' }}</div>
          </div>
          <div class="border rounded p-3">
            <div class="text-gray-500">账号</div>
            <div class="mt-1 text-gray-900">{{ userInfo?.account }}</div>
          </div>
          <div class="border rounded p-3">
            <div class="text-gray-500">加入时间</div>
            <div class="mt-1 text-gray-900">{{ formatDate(userInfo?.createTime) }}</div>
          </div>
        </div>
      </div>

      <div class="my-6 border-t border-gray-100"></div>

      <div>
        <h3 class="text-lg font-medium text-gray-900 mb-3">解题统计</h3>
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
          <div class="border rounded p-4 text-center">
            <div class="text-gray-500">已解决题目</div>
            <div class="text-2xl font-bold text-blue-600 mt-1">{{ userInfo?.solved ?? 0 }}</div>
          </div>
          <div class="border rounded p-4 text-center">
            <div class="text-gray-500">提交总数</div>
            <div class="text-2xl font-bold text-blue-600 mt-1">{{ userInfo?.submit ?? 0 }}</div>
          </div>
          <div class="border rounded p-4 text-center">
            <div class="text-gray-500">解题成功率</div>
            <div class="text-2xl font-bold text-blue-600 mt-1">{{ solveRate }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
</style>
